package retrofit2.harmony.ui.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.webengine.Navigator;
import ohos.agp.components.webengine.ResourceRequest;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import retrofit2.harmony.Constant;
import retrofit2.harmony.ResourceTable;

/**
 * WebView页面
 */
public class WebSlice extends AbilitySlice {
    private WebView vWebView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_web);
        findView();
        bindView();
        setData(intent);
    }

    private void findView() {
        vWebView = (WebView) findComponentById(ResourceTable.Id_web_view);
    }

    private void bindView() {
        vWebView.getWebConfig().setJavaScriptPermit(true);
        vWebView.setWebAgent(new WebAgent() {
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                //直接交由当前WebView加载，而不是跳转到外部浏览器
                return true;
            }
        });
    }

    private void setData(Intent intent) {
        String link = intent.getStringParam(Constant.KEY_WEB_LINK);
        vWebView.load(link);
    }

    @Override
    protected void onBackPressed() {
        Navigator navigator = vWebView.getNavigator();
        if (navigator.canGoBack()) {
            navigator.goBack();
            return;
        }
        super.onBackPressed();
    }
}